<template>
  <div class="simple-chart" :class="{full: isFull}">
    <div class="simple-chart-tool" v-if="maxable">
      <i class="el-icon-full-screen" v-show="!isFull" @click="onMax"></i>
      <i class="el-icon-minus" v-show="isFull" @click="onMin"></i>
    </div>
    <div class="simple-chart-inner" ref="main">
    </div>
  </div>
</template>

<script>
/* eslint-disable */
import * as echarts from 'echarts';
import {debounce} from '@xdh/my/ui/lib/utils/util';
import {addResizeListener, removeResizeListener} from 'element-ui/lib/utils/resize-event'

export default {
  name: 'simple-chart',
  cnName: 'simple-chart',
  props: {
    options: Object,
    maxable: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isFull: false
    }
  },
  created() {
    this.proxyResize = debounce(this.resize, 50)
  },
  methods: {
    init() {
      this.chart = echarts.init(this.$refs.main);
      this.$nextTick(_ => {
        this.chart.setOption(this.options)
      })

      // 绑定echarts事件
      Object.entries(this.$listeners)
        .forEach(([name, handler]) => {
          this.chart.on(name, handler)
        })
      addResizeListener(this.$refs.main, this.proxyResize)
    },
    resize() {
      if (!this.chart) return
      this.chart.resize()
    },
    dispose() {
      if (!this.chart) return
      Object.entries(this.$listeners).forEach(([name, handler]) => {
        this.chart.off(name, handler)
      })
      this.chart.dispose()
      this.chart = null
      removeResizeListener(this.$el, this.proxyResize)
    },
    onMax() {
      this.isFull = true
    },
    onMin() {
      this.isFull = false
    }
  },
  watch: {
    options(){
      this.chart.setOption(this.options)
    }
  },
  mounted() {
    this.init()
  },
  beforeDestroy() {
    this.dispose()
  }
}
</script>

<style lang="scss" scoped>
.simple-chart {
  position: relative;
  height: 100%;

  &-inner {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
  }

  &-tool {
    position: absolute;
    right: 0;
    top: -25px;
    cursor: pointer;
    z-index: 2;

    &:active {
      opacity: .8;
    }
  }

  &.full {
    top: 0;
    position: fixed !important;
    background: #031130;
    z-index: 9999;
    left: 0;
    right: 0;
    bottom: 0;

    .simple-chart-tool {
      top: 10px;
      right: 10px;
    }
  }
}
</style>
